<template>
  <div>
    <el-radio-group v-model="selectedPayType">
      <el-radio
        label="WechatPay"
        v-if="usePayTypes.find((t) => t === 'WechatPay')"
        >微信支付</el-radio
      >
      <el-radio label="AliPay" v-if="usePayTypes.find((t) => t === 'AliPay')"
        >支付宝</el-radio
      >
      <el-radio
        label="AccountBalance"
        v-if="usePayTypes.find((t) => t === 'AccountBalance') && offLineAccountBalance > 0"
        >余额<span
          >({{ offLineAccountBalanceText }})</span
        ></el-radio
      >
      <el-radio
        label="FactoryCoin"
        v-if="usePayTypes.find((t) => t === 'FactoryCoin') && accountBalance > 0"
        >工厂币<span
          >({{ accountBalanceText }})</span
        ></el-radio
      >
    </el-radio-group>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showDialog"
      width="40%"
      :show-close="false"
      :close-on-click-modal="fasle"
      :close-on-press-escape="false"
      v-if="paymentInfo"
    >
      <div
        v-if="paymentInfo.info && paymentInfo.info.payPlatformEnum === 'ALIPAY'"
        v-html="paymentInfo.info.body"
      ></div>
      <div
        v-if="paymentInfo.info && paymentInfo.info.payPlatformEnum === 'WX'"
        style="text-align: center"
      >
        <div>请使用微信扫码支付。</div>
        <vue-qr :text="paymentInfo.info.codeUrl" :size="200"></vue-qr>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="_onPaidFinish(false, null)">支付遇到问题</el-button>
        <el-button type="success" @click="_checkResult" :loading="queryResult"
          >已完成支付</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import paymentApi from '@/api/payment'
import { mapGetters } from 'vuex'
export default {
  props: {
    /**
     * 支付方式
     */
    payType: {
      type: String
    },
    /**
     * 使用支付方式
     */
    usePayTypes: {
      type: Array,
      default: () => {
        return ['AccountBalance', 'WechatPay', 'AliPay', 'FactoryCoin']
      }
    },
    /**
     * 当前余额 工厂币
     */
    accountBalance: {
      type: Number,
      default: 0
    },
    /**
     * 线下余额
     */
    offLineAccountBalance: {
      type: Number,
      default: 0
    },
    /**
     * 业务类型
     */
    businessType: {
      type: String
    },
    /**
     * 订单总额
     */
    totalAmount: {
      type: Number,
      default: 0
    }
  },
  computed: {
    ...mapGetters(['isSuperAdmin']),
    accountBalanceText () {
      if (this.isSuperAdmin) {
        return `可用：${this.accountBalance.toFixed(2)}个${
          this.totalAmount > 0 && this.accountBalance < this.totalAmount
            ? '，余额不足'
            : ''
        }`
      }
      return '*'
    },
    offLineAccountBalanceText () {
      if (this.isSuperAdmin) {
        return `可用：¥${this.offLineAccountBalance.toFixed(2)}${
          this.totalAmount > 0 && this.offLineAccountBalance < this.totalAmount
            ? '，余额不足'
            : ''
        }`
      }
      return '*'
    }
  },
  data () {
    return {
      selectedPayType: null,
      paymentInfo: null,
      showDialog: false,
      dialogTitle: '支付',
      businessId: null,
      queryResult: false
    }
  },
  methods: {
    /**
     * 发起支付
     *
     * @param {*} 业务id
     */
    startPayment (id) {
      if (
        !this.selectedPayType ||
        this.selectedPayType === null ||
        this.selectedPayType === ''
      ) {
        this.$alert('请先选择支付方式', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      if (this.isSuperAdmin) {
        if (
          this.selectedPayType === 'AccountBalance' &&
          this.offLineAccountBalance < this.totalAmount
        ) {
          this._onPaidFinish(
            false,
            '账户余额不足，请充值后在订单详情中完成支付或选择其它支付方式'
          )
          return
        }
        if (
          this.selectedPayType === 'FactoryCoin' &&
          this.accountBalance < this.totalAmount
        ) {
          this._onPaidFinish(
            false,
            '账户工厂币数量不足，请充值后在订单详情中完成支付或选择其它支付方式'
          )
          return
        }
      }

      this.businessId = id
      paymentApi
        .createPayment(id, this.selectedPayType, this.businessType)
        .then((response) => {
          this.paymentInfo = response.data
          if (this.paymentInfo.isPaid) {
            this._onPaidFinish(true, null)
          } else if (this.paymentInfo.info) {
            if (this.paymentInfo.info.payPlatformEnum === 'ALIPAY') {
              this.dialogTitle = '支付宝支付'
              this.showDialog = true
              this._queryResult()
            } else if (this.paymentInfo.info.payPlatformEnum === 'WX') {
              this.dialogTitle = '微信支付'
              this.showDialog = true
              this._queryResult()
            } else {
              this._onPaidFinish(false, '支付信息错误')
            }
          } else {
            this._onPaidFinish(false, '支付信息错误')
          }
        })
    },
    /**
     * 支付结果
     */
    _onPaidFinish (success, message) {
      this.$emit('paid-finished', {
        success,
        message
      })
      this.showDialog = false
    },
    /**
     * 验证支付结果
     */
    _checkResult () {
      this.queryResult = true
      paymentApi
        .queryPayment(this.businessId, this.businessType)
        .then((response) => {
          if (response.data.name === 'Created') {
            this._onPaidFinish(false, '暂未查询到支付结果，请稍后查看')
          } else if (response.data.name === 'Success') {
            this._onPaidFinish(true, null)
          } else {
            this._onPaidFinish(false, '订单支付结果验证失败，请联系管理员')
          }
        })
    },
    /**
     * 轮询支付结果
     */
    _queryResult () {
      if (!this.queryResult) {
        setTimeout(() => {
          paymentApi
            .queryPayment(this.businessId, this.businessType)
            .then((response) => {
              if (response.data.name === 'Created') {
                this._queryResult()
              } else if (response.data.name === 'Success') {
                this._onPaidFinish(true, null)
              } else {
                this._onPaidFinish(false, '订单支付结果验证失败，请联系管理员')
              }
            })
        }, 2000)
      }
    }
  },
  mounted () {
    this.selectedPayType = this.payType
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
</style>
